package com.nodecollege.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryVO;
import com.nodecollege.cloud.common.model.po.UpmsApp;
import com.nodecollege.cloud.common.model.po.UpmsAppResource;
import com.nodecollege.cloud.common.model.po.UpmsMenu;
import com.nodecollege.cloud.common.model.vo.AppResourceTreeVO;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.common.utils.RedisUtils;
import com.nodecollege.cloud.dao.mapper.UpmsApiMapper;
import com.nodecollege.cloud.dao.mapper.UpmsAppMapper;
import com.nodecollege.cloud.dao.mapper.UpmsMenuMapper;
import com.nodecollege.cloud.service.AppService;
import com.nodecollege.cloud.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LC
 * @date 2019/12/17 20:10
 */
@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private UpmsAppMapper upmsAppMapper;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UpmsMenuMapper upmsMenuMapper;

    @Autowired
    private UpmsApiMapper upmsApiMapper;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 查询应用列表
     *
     * @param queryVO
     * @return
     */
    @Override
    public NCResult<UpmsApp> getAppList(QueryVO<UpmsApp> queryVO) {
        List<UpmsApp> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(queryVO.getPageSize())) {
            list = upmsAppMapper.selectListByMap(queryVO.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
            if (queryVO.isSort()) {
                page.setOrderBy(queryVO.getSortKey() + " " + queryVO.getSortDirection());
            }
            list = upmsAppMapper.selectListByMap(queryVO.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 查询应用列表缓存
     *
     * @return
     */
    @Override
    public List<UpmsApp> getAppListCache() {
        List<UpmsApp> list = redisUtils.getList("upms:appList", UpmsApp.class);
        if (list != null) {
            return list;
        }
        list = upmsAppMapper.selectListByMap(null);
        redisUtils.set("upms:appList", list, 24 * 60 * 60);
        return list;
    }

    /**
     * 清除应用列表缓存
     */
    @Override
    public void clearAppListCache() {
        redisUtils.delete("upms:appList");
    }

    /**
     * 增加应用
     *
     * @param upmsApp
     */
    @Override
    public void addApp(UpmsApp upmsApp) {
        NCUtils.nullOrEmptyThrow(upmsApp.getAppCode(), new UpmsException("-1", "应用代码不能为空"));
        NCUtils.nullOrEmptyThrow(upmsApp.getAppName(), new UpmsException("-1", "应用名称不能为空"));
        NCUtils.nullOrEmptyThrow(upmsApp.getAppPath(), new UpmsException("-1", "应用路径不能为空"));
        NCUtils.nullOrEmptyThrow(upmsApp.getAppType(), new UpmsException("-1", "应用类型不能为空"));

        UpmsApp query = new UpmsApp();
        query.setAppPath(upmsApp.getAppPath());
        List<UpmsApp> exAppList = upmsAppMapper.selectListByMap(new QueryVO<>(query).toMap());
        NCUtils.notNullOrNotEmptyThrow(exAppList, new UpmsException("-1", "应用路径已使用！"));

        query.setAppPath(null);
        query.setAppCode(upmsApp.getAppCode());
        exAppList = upmsAppMapper.selectListByMap(new QueryVO<>(query).toMap());
        NCUtils.notNullOrNotEmptyThrow(exAppList, new UpmsException("-1", "应用代码已使用！"));

        upmsApp.setState(NCConstants.INT_1);
        upmsAppMapper.insertSelective(upmsApp);

        UpmsMenu upmsMenu = new UpmsMenu();
        upmsMenu.setMenuName(upmsApp.getAppName());
        upmsMenu.setMenuCode(upmsApp.getAppCode());
        upmsMenu.setMenuType(NCConstants.INT_0);
        upmsMenu.setMenuSource(NCConstants.INT_0);
        upmsMenu.setParentId(NCConstants.LONG_0);
        upmsMenu.setAppId(upmsApp.getAppId());
        upmsMenu.setPath(upmsApp.getAppPath());
        upmsMenu.setNum(NCConstants.INT_0);
        upmsMenu.setState(NCConstants.INT_0);
        menuService.addMenu(upmsMenu);
    }

    /**
     * 修改应用
     *
     * @param upmsApp
     */
    @Override
    public void updateApp(UpmsApp upmsApp) {
        NCUtils.nullOrEmptyThrow(upmsApp.getAppId(), new UpmsException("-1", "应用主键不能为空！"));
        UpmsApp exit = upmsAppMapper.selectByPrimaryKey(upmsApp.getAppId());
        NCUtils.nullOrEmptyThrow(exit, new UpmsException("-1", "该应用不存在！"));

        if (NCUtils.isNotNullOrNotEmpty(upmsApp.getAppPath())) {
            UpmsApp query = new UpmsApp();
            query.setAppPath(upmsApp.getAppPath());
            List<UpmsApp> exAppList = upmsAppMapper.selectListByMap(new QueryVO<>(query).toMap());
            if (exAppList.size() >= 1 && !exAppList.get(0).getAppId().equals(upmsApp.getAppId())) {
                throw new UpmsException("-1", "应用路径已存在！");
            }
        }

        if (NCUtils.isNotNullOrNotEmpty(upmsApp.getAppCode())) {
            UpmsApp query = new UpmsApp();
            query.setAppCode(upmsApp.getAppCode());
            List<UpmsApp> exAppList = upmsAppMapper.selectListByMap(new QueryVO<>(query).toMap());
            if (exAppList.size() >= 1 && !exAppList.get(0).getAppId().equals(upmsApp.getAppId())) {
                throw new UpmsException("-1", "应用代码已存在！");
            }
        }

        UpmsApp update = new UpmsApp();
        update.setAppId(upmsApp.getAppId());
        update.setAppName(upmsApp.getAppName());
        update.setAppCode(upmsApp.getAppCode());
        update.setAppPath(upmsApp.getAppPath());
        update.setHealthPath(upmsApp.getHealthPath());
        update.setNum(upmsApp.getNum());
        upmsAppMapper.updateByPrimaryKeySelective(update);
        clearAppListCache();
    }

    /**
     * 删除应用
     *
     * @param appId
     */
    @Override
    public void delApp(Long appId) {
        NCUtils.nullOrEmptyThrow(appId, new UpmsException("-1", "应用主键不能为空！"));
        UpmsApp exit = upmsAppMapper.selectByPrimaryKey(appId);
        NCUtils.nullOrEmptyThrow(exit, new UpmsException("-1", "该应用不存在！"));

        UpmsMenu query = new UpmsMenu();
        query.setAppId(exit.getAppId());
        List<UpmsMenu> exitMenu = upmsMenuMapper.selectListByMap(new QueryVO<>(query).toMap());
        if (exitMenu.size() > 1) {
            throw new UpmsException("-1", "请先删除该应用所有资源信息！");
        }

        UpmsApp del = new UpmsApp();
        del.setAppId(exit.getAppId());
        del.setState(NCConstants.INT_NEGATIVE_1);
        upmsAppMapper.updateByPrimaryKeySelective(del);
        clearAppListCache();
    }
}
